package cn.edu.tju.wallet.controller;

import cn.edu.tju.core.model.HttpResult;
import cn.edu.tju.core.model.ResultCodeEnum;
import cn.edu.tju.wallet.domain.VirtualWallet;
import cn.edu.tju.wallet.dto.RechargeRequestDTO;
import cn.edu.tju.wallet.service.RechargeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 充值控制器
 */
@RestController
@RequestMapping("/api/wallet/recharge")
@Tag(name = "钱包充值", description = "用户充值接口")
public class RechargeController {

    @Autowired
    private RechargeService rechargeService;

    /**
     * 充值接口
     *
     * @param request 充值请求参数
     * @return 充值结果
     */
    @PostMapping
    @Operation(summary = "充值", description = "用户充值，系统会自动应用充值规则计算奖励")
    public HttpResult<VirtualWallet.DepositResult> recharge(@Valid @RequestBody RechargeRequestDTO request) {
        try {
            // 参数验证（@Valid会自动验证，这里做额外业务验证）
            if (request.getUserId() == null || request.getUserId() <= 0) {
                return HttpResult.failure(ResultCodeEnum.PARAM_ERROR, "用户ID不能为空");
            }
            if (request.getAmount() == null || request.getAmount().compareTo(java.math.BigDecimal.ZERO) <= 0) {
                return HttpResult.failure(ResultCodeEnum.PARAM_ERROR, "充值金额必须大于0");
            }

            VirtualWallet.DepositResult result = rechargeService.recharge(request.getUserId(), request.getAmount());
            return HttpResult.success(result);
        } catch (IllegalArgumentException e) {
            return HttpResult.failure(ResultCodeEnum.PARAM_ERROR, e.getMessage());
        } catch (IllegalStateException e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, e.getMessage());
        } catch (RuntimeException e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, e.getMessage());
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "充值失败: " + e.getMessage());
        }
    }
}